const Router = require("@koa/router");
const router = new Router();
const { UserModel } = require("../database/index");

router.get("/users", async (ctx, next) => {
  const data = await UserModel.findAll();
  ctx.body = {
    code: 200,
    msg: "success",
    data,
  };
});

// ctx.body = {
//   code: 200,
//   msg: "success",
//   data: {
//     message: "login success",
//   },
// };

router.get("/getAllUser", async (ctx) => {
  ctx.body = {
    code: 200,
    msg: "success",
    data: [
      { name: "zs", age: 21 },
      { name: "lishi", age: 21 },
    ],
  };
});

router.post("/login", async (ctx) => {
  const { username, password } = ctx.request.body;
  console.log(username, password);
  const user = await UserModel.findAll({
    where: { username }
  });
  if (user.length === 0) {
    ctx.body = {
      code: 500,
      msg: "用户不存在"
    };
  } else {
    if (user[0].password !== password) {
      ctx.body = {
        code: 500,
        msg: "密码错误"
      };
    } else {
      ctx.body = {
        code: 200,
        data: user
      };
    }
  }
  console.log(user.length)
});
router.post("/register", async (ctx) => {
  //异步操作，加await
  const data = await UserModel.create(ctx.request.body);
  console.log(data)
  if (jane != "" || null) {
    ctx.body = {
      code: 200,
      msg: "success",
      data
    };
  } else {
    ctx.body = {
      code: 500,
      msg: "error"
    };
  }
});
router.post("/addUser", async (ctx, next) => {
  try {
    const data = await UserModel.create(ctx.request.body);
    if (data != "" || null) {
      ctx.body = {
        code: 200,
        msg: "success",
        data
      };
    } else {
      ctx.body = {
        code: 200,
        msg: "error"
      };
    }
  } catch (error) {
    console.log(error.message)
    let msg = error.errors[0].message
    ctx.body = {
      code: 500,
      msg
    };
  }
});
module.exports = router;
